#include "NUC123.h"
#include <CoOS.h>	

/* Private function prototypes -----------------------------------------------*/
#ifdef __GNUC__
  /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
     set to 'Yes') calls __io_putchar() */
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
  #define PUT_PROTOYPE int __io_write(char *ptr, int len)
  #define GET_PROTOYPE int __io_read(char *ptr, int len)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

void ShowChar(U8 u8Char)
{
	printf("%c\n", u8Char); 
}

void (*SetChar)(U8 u8Data) = ShowChar;

void UART0_IRQHandler(void)
{
	U8 u8InChar = 0xFF;
	U32 u32IntSts = UART0->ISR;

	if(u32IntSts & UART_ISR_RDA_INT_Msk)
	{
		UART0->ISR = 0;
		/* Get all the input characters */
		while(UART_IS_RX_READY(UART0))
		{
			/* Get the character from UART Buffer */
			u8InChar = UART_READ(UART0);
			SetChar(u8InChar);
		}
	}
}

void IO_Init()
{
	//SetChar = ShowChar;
	/* Reset IP */
	SYS_ResetModule(UART0_RST);

	/* Configure UART0 and set UART0 Baudrate */
	UART_Open(UART0, 115200);

	UART_EnableInt(UART0, UART_IER_RDA_IEN_Msk);
}

void IO_Register(void(*Fun)(U8))
{
	SetChar = Fun;
}

PUTCHAR_PROTOTYPE
{
	if(ch == 10)
	{
		char c = 13;
		UART_Write(UART0, &c, 1);
	}
	UART_Write(UART0, &ch, 1);
	return ch;
}

PUT_PROTOYPE
{
	return UART_Write(UART0, ptr, len);
}

GET_PROTOYPE
{
	return UART_Read(UART0, ptr, len);
}
